package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.basic.util.AjaxResult;
import cn.itsource.pethome.basic.util.HttpClientUtils;
import cn.itsource.pethome.user.constant.WechatConstant;
import cn.itsource.pethome.user.domain.WeChatUser;
import cn.itsource.pethome.user.domain.dto.WechatUserDto;
import cn.itsource.pethome.user.service.IWechatService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * 微信相关控制层
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;

    /**
     * 登录扫码
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        //获取二维码
        String code_url = WechatConstant.CODE_URL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        //进行重定向跳转
        return "redirect:" + code_url ;
    }

    /**
     * 通过回调url获取到code
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callBack(String code){
        //进行重定向跳转
        return "redirect:http://localhost:8081/callback.html?code=" + code;
    }

    /**
     * 获取token
     * @return
     */
    @PostMapping("/accesstoken")
    @ResponseBody
    public AjaxResult accessToken(@RequestBody  String code){
        try {
            JSONObject jsonObject = JSON.parseObject(code);
            String code1 = jsonObject.getString("code");
            Map<String,Object> map =  wechatService.handleCallBack(code1);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }

    }

    /**
     * 微信用户绑定
     * @param wechatUserDto 微信用户临时参数
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult accessToken(@RequestBody WechatUserDto wechatUserDto){
        try {
            //微信用户绑定
            Map<String,Object> map =  wechatService.wechatUserBinder(wechatUserDto);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }

    }
}
